const { ipcRenderer } = require('electron')


// 接收主进程发送来的消息
ipcRenderer.on('main-to-page', (event, message) => {
    console.log(message)
})

// 发送接收异步消息
ipcRenderer.on('two-way-reply', (event, arg) => {
    console.log(arg)
})
ipcRenderer.send('two-way', "asyn message1")

// 发送接收同步消息
console.log(ipcRenderer.sendSync('two-way-syn', "syn message1"))

// 协议选择操作相关
let selector = document.querySelector("#protocol-type");
selector.onchange = (e) => {
    let selector_value = selector.value;
    console.log(selector_value)
}

// 主机地址
let host = document.querySelector("#host");
host.onblur = (e) => {
    if (isValidIP(host.value) == false) {
        if (host.classList.contains("is-valid") == true) {
            host.classList.remove('is-valid')
        }
        host.classList.add('is-invalid')
        host.nextElementSibling.classList.replace("d-none", "d-block")
        host.focus()
        return
    }else{
        if (host.classList.contains("is-invalid") == true) {
            host.classList.remove('is-invalid')
        }
        host.classList.add('is-valid')
        host.nextElementSibling.classList.replace("d-block", "d-none")
    }
    console.log(host.value)
}

// 主机端口
let port = document.querySelector("#port");
port.onblur = (e) => {
    if (isValidPort(port.value) == false) {
        if (port.classList.contains("is-valid") == true) {
            port.classList.remove('is-valid')
        }
        port.classList.add('is-invalid')
        port.nextElementSibling.classList.replace("d-none", "d-block")
        port.focus()
        return
    }else{
        if (port.classList.contains("is-invalid") == true) {
            port.classList.remove('is-invalid')
        }
        port.classList.add('is-valid')
        port.nextElementSibling.classList.replace("d-block", "d-none")
    }
}

// 清空日志
let clear_log = document.querySelector("#clear-log")
let log = document.querySelector("#log")
console.log(log.scrollHeight)
console.log(log.scrollTop)
log.scrollTop = log.scrollHeight
console.log(log.scrollTop)
clear_log.onclick = (e) => {
    log.innerHTML = ""
}

// 存历史连接
// let connect = [
//     {
//         type: "wss",
//         host: "127.0.0.1",
//         port: 3306,
//     },
//     {
//         type: "tcp",
//         host: "192.168.10.160",
//         port: 9501,
//     },
//     {
//         type: "udps",
//         host: "127.0.0.1",
//         port: 8080,
//     },
// ]
// localStorage.setItem("history_connect", JSON.stringify(connect))

// 读取历史连接
let history_connect_info = document.querySelector(".history-connect-info")
function getHistoryConnect () {
    let history_connect = localStorage.getItem("history_connect")
    if (history_connect) {
        history_connect = JSON.parse(history_connect)
        for (let i = 0; i < history_connect.length; i++) {
            if (history_connect[i] == null) continue
            history_connect_info.innerHTML += `
            <li class="list-group-item p-2 history-info">
                <button type="button" 
                class="btn btn-light btn-sm btn-block" 
                onclick="re_connect_history(this)" 
                data-type="`+history_connect[i].type+`"
                data-host="`+history_connect[i].host+`"
                data-port="`+history_connect[i].port+`">
                    `+history_connect[i].type+`://`+history_connect[i].host+`:`+history_connect[i].port+`
                </button>
            </li>`
        }
    }
}
getHistoryConnect()


//恢复历史连接
function re_connect_history (e) {
    let type_value = e.attributes['data-type'].value
    let host_value = e.attributes['data-host'].value
    let port_value = e.attributes['data-port'].value
    host.value = host_value
    port.value = port_value
    selector.value = type_value
}

// 清除历史连接
let clear_link = document.querySelector("#clear-link")
let history_infos = document.getElementsByClassName("history-info")
clear_link.onclick = () => {
    removeHistoryConnect()
    localStorage.removeItem("history_connect")
}
function removeHistoryConnect () {
    let length = history_infos.length
    for (let i = length; i > 0; i--) {
        history_connect_info.removeChild(history_infos[i-1])
    }
}

// 建立或打开连接
let connection = document.querySelector("#connect")
let connection_info
connection.onclick = () => {
    if (selector.value == '') {
        selector.focus()
        return
    }else if (host.value == '') {
        host.focus()
        return
    }else if (port.value == '') {
        port.focus()
        return
    }
    connection_info = {
        type: selector.value,
        host: host.value,
        port: port.value
    }
    addHistoryConnect(connection_info)
    removeHistoryConnect()
    getHistoryConnect()
    if (connection_info.type == "wss") {
        ws()
    }else{
        ipcRenderer.send('connection', JSON.stringify(connection_info)) //{status:200, conn:connection}
    }
}
function addHistoryConnect (connection) {
    let hc = localStorage.getItem("history_connect")
    if (hc) {
        hc = JSON.parse(hc)
        if (hc.length == 3) {
            hc.pop()
        }
        hc.unshift(connection)
    }else{
        hc = [connection]
    }
    localStorage.setItem("history_connect", JSON.stringify(hc))
}

// 关闭连接
let close = document.querySelector("#close")
close.onclick = () => {
    if (connection_info.type == "wss") {
        wss.close()
    }else{
        ipcRenderer.send('close', "close")
    }
}

let connect_status = "no"
ipcRenderer.on('connection-reply', (event, arg) => {
    console.log(arg)
    if (arg == 201) {
        connect_status = "yes"
        connection.classList.replace("d-block", "d-none")
        close.classList.replace("d-none", "d-block")
    }else if (arg == 301 || arg == 401){
        connect_status = "no"
        close.classList.replace("d-block", "d-none")
        connection.classList.replace("d-none", "d-block")
    }else{
        ab2str(arg,function(str){
            console.log(str)
            addLog("re", str)
        });
    }
})

// 发送消息
let send = document.querySelector("#send")
let send_message = document.querySelector("#send-message")
send.onclick = () => {
    console.log(connect_status)
    if (connect_status == "yes") {
        let message = send_message.value
        if (message == "") {
            message.focus()
            return
        }
        if (connection_info.type == "wss") {
            wss.send(message)
        }else{
            ipcRenderer.send('send', message)
        }
        addLog("send", message)

    }
}
function addLog (type, data) {
    let time = currentTime();
    if (type == "send") {
        log.innerHTML += `
            <li class="list-group-item list-group-item-action p-0 border-0">
                <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">
                        <span class="badge badge-primary">Send</span>
                        `+connection_info.type+`://`+connection_info.host+`:`+connection_info.port+`
                    </h6>
                    <small class="d-none d-sm-block" style="color: #495057">`+time+`</small>
                </div>
                <p class="mb-1">`+data+`</p>
            </li>
        `
    }else{
        log.innerHTML += `
            <li class="list-group-item list-group-item-action p-0 border-0">
                <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">
                        <span class="badge badge-success">Receive</span>
                        `+connection_info.type+`://`+connection_info.host+`:`+connection_info.port+`
                    </h6>
                    <small class="d-none d-sm-block" style="color: #495057">`+time+`</small>
                </div>
                <p class="mb-1">`+data+`</p>
            </li>
        `
    }
    log.scrollTop = log.scrollHeight
}



//验证ip
function isValidIP(ip) {
    let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return reg.test(ip);
}
// 验证端口
function isValidPort(port) {
    let reg=/^(\d)+$/g;
    if(reg.test(port)&&parseInt(port)<=65535&&parseInt(port)>=0){
        return true;
    }else{
        return false;
    }
}
// ArrayBuffer转字符串
function ab2str(u,f) {
    var b = new Blob([u]);
    var r = new FileReader();
    r.readAsText(b, 'utf-8');
    r.onload = function (){if(f)f.call(null,r.result)}
}
//获取当前时间
function currentTime() {
    let d = new Date(),
        str = '';
    str += d.getFullYear() + '-'; //获取当前年份
    str += d.getMonth() + 1 + '-'; //获取当前月份（0——11）
    str += d.getDate() + ' ';
    str += d.getHours() + ':';
    str += d.getMinutes() + ':';
    str += d.getSeconds();
    return str;
}

let wss
function ws () {
    let ws_url = 'ws://'+host.value+':'+port.value
    wss = new WebSocket(ws_url)
    wss.onopen = () => {
        console.log("wss success")
        wss.send("connect")
        connect_status = "yes"
        connection.classList.replace("d-block", "d-none")
        close.classList.replace("d-none", "d-block")
    }
    wss.onclose = function(e){
        console.log("服务器关闭");
        connect_status = "no"
        close.classList.replace("d-block", "d-none")
        connection.classList.replace("d-none", "d-block")
    }
    wss.onerror = function(){
        console.log("连接出错");
        connect_status = "no"
        close.classList.replace("d-block", "d-none")
        connection.classList.replace("d-none", "d-block")
    }
    wss.onmessage = function(e){
        addLog("rec", e.data)
    }
}